<?php

namespace App\Models\Teaching;

use App\Models\FormInstance;
use App\Models\System\Term;
use App\Models\System\User;
use App\Models\Traits\HasManagable;
use Illuminate\Database\Eloquent\Model;

class TeachingSubject extends Model
{
    //use HasManagable;
    protected $table = 'teaching_subject';
    protected $guarded = [];
    protected $hidden = ['updated_at'];
    protected $appends = [
        'subject_set',
        'grade_set',
        'class_set',
    ];

    public function term()
    {
        return $this->hasOne(Term::class, 'id', 'data_version_id');
    }

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }

    public function creator()
    {
        return $this->hasOne(User::class, 'id', 'creator_id');
    }


    public function instance()
    {
        return $this->hasOne(FormInstance::class, 'id', 'form_instance_id');
    }

    public function getSubjectSetAttribute(){
        $subject = !empty($this->attributes['subject_dic_items']) ? $this->attributes['subject_dic_items'] : '';

        if(!$subject){
            return [];
        }

        return json_decode($subject, true);
    }

    public function getGradeSetAttribute(){
        $grade = !empty($this->attributes['grade_dic_items']) ? $this->attributes['grade_dic_items'] : '';

        if(!$grade){
            return [];
        }

        $gradeItems = json_decode($grade, true);

        $result = [
            'grade_items' => $gradeItems,
            'grades' => collect($gradeItems)->pluck('selectValue')->implode(','),
            'grade_dic_ids' => collect($gradeItems)->pluck('optionId')->toArray()
        ];

        return $result;
    }

    public function getClassSetAttribute(){
        $class = !empty($this->attributes['class_item']) ? $this->attributes['class_item'] : '';

        if(!$class){
            return [];
        }

        $classItems = json_decode($class, true);

        $result = [
            'class_items' => $classItems,
            'classes' => collect($classItems)->pluck('selectValue')->implode(','),
            'class_dic_ids' => collect($classItems)->pluck('optionId')->toArray()
        ];

        return $result;
    }
}
